<?php

include_once dirname(__FILE__) . '/../system/Model.php';

// wechat OAuth class
class WechatSdk extends Model{

    const QR_LIMIT_SCENE = 'QR_LIMIT_SCENE';
    const QR_SCENE = 'QR_SCENE';

    //@检查openid存在
    public static function checkOpenIdExist($openid) {
        $result = mysql_query("SELECT COUNT(client_wechat_openid) AS count FROM clients WHERE client_wechat_openid = '" . $openid . "';");
        $result = mysql_fetch_array($result);
        return $result['count'] == 1;
    }

    //@获取服务号access token
    public static function getServiceAccessToken() {
        // SAMPLE https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc89fd01ce526721c&secret=916e07fa86c5111643474c4fe05667cb
        $RequestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET;
        $Result = Curl::get($RequestUrl);
        $Result = json_decode($Result, true);
        return $Result['access_token'];
    }

    //@获取推广二维码ticket
    public static function getCQrcodeTicket($access_token, $scene, $ticketType = self::QR_LIMIT_SCENE) {

        // 临时的支持 0 ~ 4294967295
        // 永久仅支持 0 ~ 100000
        //POST => {"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}
        //URL  => https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN

        $RequestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $access_token;
        $PostData = array(
            'action_name' => $ticketType,
            'action_info' => array(
                'scene' => array(
                    'scene_id' => $scene
                )
            )
        );
        $PostData = json_encode($PostData);
        $Result = Curl::post($RequestUrl, $PostData);
        $Result = json_decode($Result, true);
        return $Result['ticket'];
    }

    //@获取推广图片
    public static function getCQrcodeImage($ticket) {
        return 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($ticket);
    }

    //@获取用户授权凭证code
    public static function getAccessCode($redirect_uri, $scope) {
        $request_access_token_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . APPID . "&redirect_uri=[REDIRECT_URI]&response_type=code&scope=[SCOPE]#wechat_redirect";
        if (empty($_GET['code'])) {
            // 未授权而且是拒绝
            if (!empty($_GET['state'])) {
                return FALSE;
            } else {
                // 未授权
                $redirect_uri = urlencode($redirect_uri);
                $RequestUrl = str_replace("[REDIRECT_URI]", $redirect_uri, $request_access_token_url);
                $RequestUrl = str_replace("[SCOPE]", $scope, $RequestUrl);
                // 获取授权
                header("location:" . $RequestUrl);
                exit(0);
            }
        } else {
            // 授权成功 返回 access_token 票据
            return $_GET['code'];
        }
    }

    //@获取用户信息
    public static function getUserInfo($access_token, $openid) {
        // 获取用户信息 scope 必须为 snsapi_userinfo
        //{
        //   "openid":" OPENID",
        //   " nickname": NICKNAME,
        //   "sex":"1",
        //   "province":"PROVINCE"
        //   "city":"CITY",
        //   "country":"COUNTRY",
        //    "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", 
        //   "privilege":[
        //    "PRIVILEGE1"
        //    "PRIVILEGE2"
        //    ]
        //}
        $RequestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $Result = Curl::get($RequestUrl);
        $Result = json_decode($Result, true);
        return $Result;
    }

    // @获取用户授权access token，使用code凭证
    public static function getAccessToken($code) {
        // @return object{access_token,openid}
        //    {
        //       "access_token":"ACCESS_TOKEN",
        //       "expires_in":7200,
        //       "refresh_token":"REFRESH_TOKEN",
        //       "openid":"OPENID",
        //       "scope":"SCOPE"
        //    }
        $RequestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . APPID . "&secret=" . APPSECRET . "&code=" . $code . "&grant_type=authorization_code";
        $Result = json_decode(Curl::get($RequestUrl), true);
        $_return = new stdClass();
        $_return->access_token = $Result['access_token'];
        $_return->openid = $Result['openid'];
        return $_return;
    }

    /**
     * 判断是否在微信环境，而且返回valid结果
     * @return boolean
     */
    public static function isWechat() {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        } else
        // wechat validate request
        if (isset($_GET["timestamp"]) && isset($_GET["signature"]) && isset($_GET["echostr"])) {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $tmpArr = array(TOKEN, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                echo $_GET["echostr"];
            }
        }
        return false;
    }

    /**
     * 获取关注者列表 0 - 10000
     * @param type $access_token
     * @param type $nextOpenid
     * @return type
     */
    public static function getWechatSubscriberList($access_token, $nextOpenid = '') {
        // https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
        $RequestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$access_token&next_openid=$nextOpenid";
        $Result = Curl::get($RequestUrl);
        return json_decode($Result, true);
    }

}

// HTML Helper
class Helper {

    public static function convPayMethod($method) {
        $arr = array('cash' => '现金', 'bankcard' => '银联', 'vipcard' => '会员');
        if (array_key_exists($method, $arr)) {
            return $arr[$method];
        } else {
            return '';
        }
    }

    public static function StringInsert($str, $i, $substr) {
        $startstr = "";
        $laststr = "";
        for ($j = 0; $j < $i; $j++) {
            $startstr .= $str[$j];
        }
        for ($j = $i; $j < strlen($str); $j++) {
            $laststr .= $str[$j];
        }
        $str = ($startstr . $substr . $laststr);
        return $str;
    }

    public static function tTimeFormat_vs($stringtime) {
        return Helper::tTimeFormat(strtotime($stringtime));
    }

    public static function tTimeFormat($timestamp) {
        $curTime = time();
        $space = $curTime - $timestamp;
        //1分钟
        if ($space < 60) {
            $string = "刚刚";
            return $string;
        } elseif ($space < 3600) { //一小时前
            $string = floor($space / 60) . "分钟前";
            return $string;
        }
        $curtimeArray = getdate($curTime);
        $timeArray = getDate($timestamp);
        if ($curtimeArray['year'] == $timeArray['year']) {
            if ($curtimeArray['yday'] == $timeArray['yday']) {
                $format = "%H:%M";
                $string = strftime($format, $timestamp);
                return "今天 {$string}";
            } elseif (($curtimeArray['yday'] - 1) == $timeArray['yday']) {
                $format = "%H:%M";
                $string = strftime($format, $timestamp);
                return "昨天 {$string}";
            } else {
                $string = sprintf("%d月%d日 %02d:%02d", $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
                return $string;
            }
        }
        $string = sprintf("%d年%d月%d日 %02d:%02d", $timeArray['year'], $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
        return $string;
    }

}

// wechat message sender
class Messager {

    // send plain/text to user's wechat client
    public static function sendText($access_token, $openid, $content) {
        //{
        //    "touser":"OPENID",
        //    "msgtype":"text",
        //    "text":
        //    {
        //         "content":"Hello World"
        //    }
        //}
        $RequestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
        $postData = array();
        $postData['touser'] = (string) $openid;
        $postData['msgtype'] = 'text';
        $postData['text'] = array('content' => urlencode($content));
        $Result = Curl::post($RequestUrl, urldecode(json_encode($postData)));
        return json_decode($Result, true);
    }

}
